import http from '@/utils/request.js'

// ========================================
// 知识库管理 API
// ========================================

// 创建知识库
export const createKnowledgeBase = ({
  knowledgeBaseName,
  knowledgeBaseDescription,
  isPublic = false
}) => {
  return http.post('/knowledgebase', {
    knowledgeBaseName,
    knowledgeBaseDescription,
    isPublic
  })
}

// 获取知识库列表
export const getKnowledgeBaseList = () => http.get('/knowledgebase')

// 获取知识库详情
export const getKnowledgeBaseDetail = (knowledgeBaseId) => {
  return http.get(`/knowledgebase/${knowledgeBaseId}`)
}

// 更新知识库
export const updateKnowledgeBase = (knowledgeBaseId, {
  knowledgeBaseName,
  knowledgeBaseDescription,
  isPublic
}) => {
  return http.put(`/knowledgebase/${knowledgeBaseId}`, {
    knowledgeBaseName,
    knowledgeBaseDescription,
    isPublic
  })
}

// 删除知识库
export const deleteKnowledgeBase = (knowledgeBaseId) => {
  return http.delete(`/knowledgebase/${knowledgeBaseId}`)
}

// ========================================
// 文档管理 API
// ========================================

// 上传文档（自动解析和向量化）
export const uploadDocument = ({
  filePath,
  documentTitle,
  knowledgeBaseId,
  documentAccessLevel = 'private'
}) => {
  const formData = {
    documentTitle,
    knowledgeBaseId,
    documentAccessLevel
  }
  
  return http.upload('/document/upload', filePath, formData)
}

// 批量上传文档
export const batchUploadDocuments = ({
  filePaths,
  knowledgeBaseId,
  documentAccessLevel = 'private'
}) => {
  // 由于uni-app的限制，逐个上传文件
  const uploadPromises = filePaths.map(filePath => {
    return http.upload('/document/upload', filePath, {
      knowledgeBaseId,
      documentAccessLevel
    })
  })
  
  return Promise.all(uploadPromises)
}

// 查看文档处理状态
export const getDocuments = (knowledgeBaseId) => {
  return http.get('/document', { knowledgeBaseId })
}

// 搜索文档
export const searchDocuments = ({
  keyword,
  knowledgeBaseId,
  page = 1,
  pageSize = 10
}) => {
  return http.post('/document/search', {
    keyword,
    knowledgeBaseId,
    page,
    pageSize
  })
}

// 查看特定文档详情
export const getDocumentDetail = (documentId) => {
  return http.get(`/document/${documentId}`)
}

// 查看文档的文档块列表
export const getDocumentChunks = (documentId) => {
  return http.get(`/document/${documentId}/chunks`)
}

// 重新处理文档（重新分块和向量化）
export const reprocessDocument = (documentId) => {
  return http.post(`/document/${documentId}/reprocess`)
}

// 删除文档
export const deleteDocument = (documentId) => {
  return http.delete(`/document/${documentId}`)
}

// ========================================
// 向量检索 API
// ========================================

// 语义相似度检索相关文档
export const retrieveChunks = (query, topK = 5) => {
  return http.get('/qa/retrieve-chunks', { query, topK })
}

// 生成文本向量
export const generateEmbedding = (text) => {
  return http.post('/vector/generate-embedding', { text })
}

// ========================================
// 工具函数
// ========================================

// 文件类型检查
export const SUPPORTED_FILE_TYPES = {
  'application/pdf': '.pdf',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
  'application/msword': '.doc',
  'text/plain': '.txt',
  'text/markdown': '.md'
}

// 检查文件类型是否支持
export const isFileTypeSupported = (fileType) => {
  return Object.keys(SUPPORTED_FILE_TYPES).includes(fileType)
}

// 获取文件扩展名
export const getFileExtension = (fileName) => {
  return fileName.substring(fileName.lastIndexOf('.'))
}

// 格式化文件大小
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 文档状态常量
export const DOCUMENT_STATUS = {
  PENDING: 'pending',
  PROCESSING: 'processing',
  COMPLETED: 'completed',
  FAILED: 'failed'
}

// 文档状态中文映射
export const DOCUMENT_STATUS_TEXT = {
  [DOCUMENT_STATUS.PENDING]: '等待处理',
  [DOCUMENT_STATUS.PROCESSING]: '处理中',
  [DOCUMENT_STATUS.COMPLETED]: '已完成',
  [DOCUMENT_STATUS.FAILED]: '处理失败'
}

// 获取文档状态文本
export const getDocumentStatusText = (status) => {
  return DOCUMENT_STATUS_TEXT[status] || '未知状态'
}

// 检查文档是否处理完成
export const isDocumentCompleted = (status) => {
  return status === DOCUMENT_STATUS.COMPLETED
}

// 检查文档是否处理失败
export const isDocumentFailed = (status) => {
  return status === DOCUMENT_STATUS.FAILED
}

// 检查文档是否正在处理
export const isDocumentProcessing = (status) => {
  return status === DOCUMENT_STATUS.PROCESSING
} 